package businessLogic.facade;

import businessLogic.service.ServiceFactory;
import businessLogic.service.UserService;
import businessLogic.transaction.Transaction;
import businessLogic.transaction.TransactionFactory;
import java.util.List;
import vo.UserVO;

/**
 *
 * @author Alexander
 */
public class UserFacade {

    private Transaction transaction;
    private UserService service;

    public UserFacade(int id) {
        service = ServiceFactory.getInstance().getUserService(id);
        transaction = TransactionFactory.getInstance().getTransaction(id);
    }

    public void persist(UserVO vo) {
        if (transaction.createTransaction()) {
            try {
                service.persist(vo, transaction.getTransaction());
                transaction.commit();
            } catch (Exception e) {
                transaction.rollBack();
            } finally {
                transaction.close();
            }
        }
    }

    public UserVO find(Object id) {
        if (transaction.createTransaction()) {
            try {
                return service.find(id, transaction.getTransaction());
            } finally {
                transaction.close();
            }
        }
        return null;
    }

    public boolean update(UserVO vo) {
        if (transaction.createTransaction()) {
            try {
                service.update(vo, transaction.getTransaction());
                transaction.commit();
                return true;
            } catch (Exception e) {
                transaction.rollBack();
            } finally {
                transaction.close();
            }
        }
        return false;
    }

    public boolean delete(Object id) {
        if (transaction.createTransaction()) {
            try {
                service.delete(id, transaction.getTransaction());
                transaction.commit();
                return true;
            } catch (Exception e) {
                transaction.rollBack();
                System.out.println(e.getMessage());
            } finally {
                transaction.close();
            }
        }
        return false;
    }

    public List<UserVO> getList() {
        if (transaction.createTransaction()) {
            try {
                return service.getList(transaction.getTransaction());
            } finally {
                transaction.close();
            }
        }
        return null;
    }
    
    public UserVO login(UserVO vo) {
        if (transaction.createTransaction()) {
            try {
                return service.login(vo, transaction.getTransaction());
            } finally {
                transaction.close();
            }
        }
        return null;
    }
    
}
